<template>
  <div class="service-statistics-container">
    <div class="stats-panel-head stats-form">
      <h3>
        {{$t('report.statistics.title50')}}
        <el-popover trigger="hover" class="">
          <div style="display: flex;justify-content: flex-start">
            <div >
              <div class="stats-popover-row">
                <div class="stats-popover-label service-repoart-label">{{`${$t('common.fields.serviceName.displayName')}-${$t('common.form.preview.serviceItem.colum5')}：`}}</div>
              </div>
              <div class="stats-popover-row">
                <div class="stats-popover-label service-repoart-label">{{`${$t('common.fields.serviceName.displayName')}-${$t('settingCustomer.type.cost')}：`}}</div>
              </div>
              <div class="stats-popover-row">
                <div class="stats-popover-label service-repoart-label">{{`${$t('common.fields.serviceName.displayName')}-${$t('report.staffTaskTable.label3')}：`}}</div>
              </div>
              <div class="stats-popover-row">
                <div class="stats-popover-label service-repoart-label">{{`${$t('common.fields.serviceName.displayName')}-${$t('common.part.category')}：`}}</div>
              </div>
            </div>
            <div >
              <div class="stats-popover-row">
                <div class="stats-popover-text">{{$t('report.staffTaskTable.title1')}}</div>
              </div>
              <div class="stats-popover-row">
                <div class="stats-popover-text">{{$t('report.staffTaskTable.title2')}}</div>
              </div>
              <div class="stats-popover-row">
                <div class="stats-popover-text">{{$t('report.staffTaskTable.title3')}}</div>
              </div>
              <div class="stats-popover-row">
                <div class="stats-popover-text">{{$t('report.staffTaskTable.title4')}}</div>
              </div>
            </div>
          </div>
          <stats-popover-icon slot="reference"></stats-popover-icon>
        </el-popover>
      </h3>

      <!-- start 工单类型选择 -->
      <el-select 
        v-model="taskTypeList" 
        multiple 
        clearable 
        collapse-tags
        class="task-type-select"
        :placeholder="$t('report.taskSelect.placeholder1')" 
        @change="taskTypeChange" 
        @clear="taskTypeChange"
      >
        <el-option
          v-for="item in taskTypeArr"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <!-- end 工单类型选择 -->

      <biz-team-select class="stats-team-select biz-team-select" is-auto-select-child multiple collapse :value="tag" @input="fetchData" :fetch-func="fetchTeam"/>
      <!-- <div class="stats-form-group">
        <select @change="fetchData">
          <option value="">全部</option>
          <option v-for="team in teams" :key="team.id" :value="team.id">{{team.name}}</option>
        </select> 
      </div> -->
      <div class="stats-form-group">
        <!-- <div id="date-range" class="stats-form-daterange">
          <span>{{requestParams.timeStart}} - {{requestParams.timeEnd}}</span>
          <b class="caret"></b>
        </div> -->
        <date-picker @datePicker="datePicker" />
      </div>
    </div>

    <div class="service-statistics-page-panel">
      <div class="report-head">
        <div class="stats-btn-group">
          <button type="button" :class="{'stats-checked': activeTab == 'service-usage-amount-report'}" @click="activeTab = 'service-usage-amount-report';trackEventHandler('service-usage-amount')">{{`${$t('common.fields.serviceName.displayName')}-${$t('common.form.preview.serviceItem.colum5')}`}}</button>
          <button type="button" :class="{'stats-checked': activeTab == 'service-cost-report'}" @click="activeTab = 'service-cost-report';trackEventHandler('service-cost')">{{`${$t('common.fields.serviceName.displayName')}-${$t('settingCustomer.type.cost')}`}}</button>
          <button type="button" :class="{'stats-checked': activeTab == 'service-usage-crowd-report'}" @click="activeTab = 'service-usage-crowd-report';trackEventHandler('service-usage-crowd')">{{`${$t('common.fields.serviceName.displayName')}-${$t('report.staffTaskTable.label3')}`}}</button>
          <button type="button" :class="{'stats-checked': activeTab == 'service-category-report'}" @click="activeTab = 'service-category-report';trackEventHandler('service-category')" >{{`${$t('common.fields.serviceName.displayName')}-${$t('common.part.category')}`}}</button>
        </div>
      </div>

      <keep-alive>
        <component
          :is="activeTab"
          ref="statistics"
          :request-params="computedParams"
          :chart-type="chartType"
          @export-track="exportTrack"
        ></component>
      </keep-alive>
    </div>
  </div>
</template>

<script>
/* global AMap, moment, _init_data $ */

import ServiceUsageAmountReport from './ServiceUsageAmountReport.vue';
import ServiceUsageCrowdReport from './ServiceUsageCrowdReport.vue';
import ServiceCostReport from './ServiceCostReport.vue';
import ServiceCategoryReport from './ServiceCategoryReport.vue';
// api
import * as ReportApi from '@src/api/ReportApi.ts';

export default {
  name: 'service-view',
  data(){
    return {
      activeTab: 'service-usage-amount-report',
      // teams: [],
      tag: [],
      requestParams: {
        timeStart: '',
        timeEnd: '',
        tagId: '',
        taskTypeList: [],
      },
      taskTypeList: [],
      taskTypeArr: [], // 工单类型
      chartType: 'service-item-information'
    };
  },
  computed: {
    computedParams() {
      return {
        taskTypeList: this.requestParams.taskTypeList,
        tagId: this.requestParams.tagId,
        timeStart:  this.requestParams.timeStart,
        timeEnd:  this.requestParams.timeEnd,
      }
    }
  },
  methods: {
    // 导出埋点
    exportTrack(isExportAll) {
      const tab = this.activeTab.toLocaleUpperCase().replaceAll('-', '_')
      window.parent.postMessage({
        message: 'exportTrack',
        isExportAll,
        chartType: this.chartType,
        tab
      }, '*')
    },
    fetchTeam(params){
      return this.$http.post('/security/tag/tree', {...params, ...{authKey: 'VIP_REPORT_VIEW'}})
    },
    switchTab(tab){
      this.activeTab = tab;
    },
    chooseDate(start, end){
      this.$tdOnEvent('pc：服务项目报表-日期选择事件');

      this.requestParams.timeStart = start;
      this.requestParams.timeEnd = end;

      this.$nextTick(() => {
        this.$refs.statistics.loadChartData({
          pageNum: 1,
        });
      });
    },
    fetchData(value) {
      this.$tdOnEvent('pc：服务项目报表-选择团队下拉框事件');

      // let tag = (Array.isArray(value) ? value[0] : value) || {};

      let tag = value
      this.tag = value;
      this.requestParams.tagId = tag.map(item => {return item.id}).join(',');
    
      this.$nextTick(() => {
        this.$refs.statistics.loadChartData({
          pageNum: 1,
        });
      });

      this.chartType && this.$track.commonFn.chartTrack(this.chartType, 'REPORT_SEARCH_TEAM', this.$track)
    },
    // 工单类型选择
    taskTypeChange(e){
      this.$tdOnEvent('pc：服务项目报表-选择工单类型下拉框事件');
      this.$set(this.requestParams, 'taskTypeList', e);
      
      this.$nextTick(() => {
        this.$refs.statistics.loadChartData({
          pageNum: 1,
        });
      });
      this.chartType && this.$track.commonFn.chartTrack(this.chartType, 'REPORT_SEARCH_TASKTYPE', this.$track)
    },
    // TalkingData事件埋点
    trackEventHandler(type) {
      switch (type) {
      case 'service-usage-amount':
        this.$tdOnEvent('pc：服务项目报表-服务项目-用量事件');
        break;
      case 'service-cost':
        this.$tdOnEvent('pc：服务项目报表-服务项目-费用事件');
        break;
      case 'service-usage-crowd':
        this.$tdOnEvent('pc：服务项目报表-服务项目-使用人事件');
        break;
      case 'service-category':
        this.$tdOnEvent('pc：服务项目报表-服务项目-类别事件');
        break;
      default:
        break;
      }
    },
    datePicker(data) {
      // 初始化趋势图
      const start = data[0];
      const end = data[1];
      this.requestParams.timeStart = start;
      this.requestParams.timeEnd = end;
      this.chooseDate(start, end)

      this.chartType && this.$track.commonFn.chartTrack(this.chartType, 'REPORT_SEARCH_TIME', this.$track)
    },
    // 工单类型
    async taskTypes() {
      this.taskTypeArr = [];
      const {succ, data} = await ReportApi.taskType();
      if (succ) {
        for(let key in data) {
          this.taskTypeArr.push({
            value: key,
            label: data[key]
          })
        }
      }
    },
  },
  mounted(){
    this.taskTypes();
    // init datePicker

    // init data
    // let initData = JSON.parse(JSON.stringify(window._init_data)) || {};
    // this.teams = initData.teams || [];
  },
  components: {
    [ServiceUsageAmountReport.name]: ServiceUsageAmountReport,
    [ServiceCostReport.name]: ServiceCostReport,
    [ServiceUsageCrowdReport.name]: ServiceUsageCrowdReport,
    [ServiceCategoryReport.name]: ServiceCategoryReport,
  }
}
</script>
<style lang="scss">
  .service-repoart-label {
    width: fit-content!important;
  }

  .service-statistics-container {
    padding: 10px 15px;

    .task-type-select {
      width: 220px;
      color: #606266;
      background-color: #fff;
      border: 1px solid #e0e1e2;
      border-radius: 3px;
      -webkit-appearance: none;
    }

    .biz-team-select {
      width: 260px;
    }

    .tab-list {
      display: flex;

      padding: 0;
      li {
        width: 130px;
        text-align: center;
        font-size: 16px;
        height: 40px;
        line-height: 40px;
        list-style: none;
        position: relative;
        &:hover {
          color: #409EFF;
          cursor: pointer;
        }

      }
      li.actived {
        color: #409EFF;
        &::after {
          content: '';
          position: absolute;
          width: 100%;
          height: 2px;
          background: #409EFF;
          bottom: 0;
          left: 0;
        }
      }
    }

    .load-more-data-btn {
      color: #6da9e8;
    }

    .disabled-load-more-data-btn {
      color: #9a9a9a;
    }

    .stats-task-table-header{
      display: flex;
      flex-flow: row nowrap;
      padding: 5px;

      h3{
        font-size: 14px;
        flex: 1;
        margin: 0;
        line-height: 30px;
      }

      button{
        margin-left: 5px;
      }
    }

    .service-statistics-page-panel {
      background: #fff;

      .report-head {
        text-align: center;
        /*padding: 0 10px;*/
      }
    }
  }
</style>
